package cn.edu.xmu.tangzk.scala.byexs

import scala.annotation.tailrec

/**
 * 求f(a)*...*f(b)的积
 */
object Ex05_2_2 {

    val EmptyProduct = 1

    def linearProduct(f: Int => Int)(a: Int, b: Int): Int = {
        if (a > b) EmptyProduct
        else { f(a) * linearProduct(f)(a + 1, b) }
    }

    def product(f: Int => Int)(a: Int, b: Int): Int = {
        @tailrec def productIter(a: Int, result: Int): Int = {
            if (a > b) result
            else {
                productIter(a + 1, result * f(a))
            }
        }
        productIter(a, EmptyProduct)
    }

    def main(args: Array[String]) {
        val result0 = linearProduct(x => x)(2, 4)
        val result1 = product(x => x)(2, 4)
        println(result0, result1)
        assert(result0 == result1)
    }

}